import {batchDeleteItem, changeSelectState} from "@mall/api/shopCart";
import { getStoreDetail } from '@src/api/mall/store'
import router from "@src/router";
import {preOrderFun} from "@mall/api/order";
import {deleteOrder} from "@src/api/order";

Component({
  properties: {
    detail: {
      type: Object,
      value: {},
    },
    headerShow: {
      type: Boolean,
      value: true
    },
    footerShow: {
      type: Boolean,
      value: true
    },
    themeTitleColor: {
      type: String
    },
    themeColor: {
      type: String
    },
    storeNo: {
      type: String
    }
  },
  observers: {
    'detail': function (detail) {
      if (!detail) {
        this.setData({totalFee: 0, selectAll: false, cartItems: []})
        return;
      }

      let cartItems = JSON.parse(JSON.stringify(detail.items));
      let invalidItems = JSON.parse(JSON.stringify(detail.invalidItems));
      for (let i = 0; i < cartItems.length; i++) {
        cartItems[i].disable = false;
      }

      for (let i = 0; i < invalidItems.length; i++) {
        invalidItems[i].disable = true;
        cartItems.push(invalidItems[i]);
      }

      this.setData({
        cartItems: cartItems,
        selectCartItems: [],
        selectAll: false,
        totalFee: 0,
      })
      if (detail.errorCode === 0) {
        this.initCart(this.data.cartItems);
      }
    }
  },
  data: {
    totalFee: 0,
    cartItems: [],
    selectCartItems: [],
    selectAll: false,
  },
  methods: {
    initCart(cartItems) {
      let totalFee = 0;
      let selectAll = true;
      let selectCartItems = []
      for (let i = 0; i < cartItems.length; i++) {
        let cartItem = cartItems[i];
        if (cartItem.selected && !cartItem.disable) {
          selectCartItems.push(cartItem)
          var childrenPrice = 0;
          if(cartItem.children){
            cartItem.children.forEach((item,index)=>{
              childrenPrice+=(item.price) * (item.num*cartItem.num)
            })
          }
          totalFee += cartItem.price * cartItem.num + childrenPrice;
        } else {
          selectAll = false;
        }
      }
      this.setData({totalFee: totalFee, selectAll: selectAll, selectCartItems: selectCartItems})
    },
    toCollDetail(e){
     const goodsSerial = e.currentTarget.dataset.goodsserial;
     const storeId = e.currentTarget.dataset.storeid;
     const collStatus = true
      router.push({ name: "mall/goods-detail", params:{goodsSerial,storeId,collStatus}  })
    },
    handleClear() {
      wx.showModal({
        title: "温馨提示", content: "是否需要清空购物车?",
        showCancel: true,
        success: sm => {
          if (sm.confirm) {
            let cartItemDel = [];
            this.data.cartItems.forEach(item => {
              let temp = {
                cartItemId: item.cartItemId,
                goodsId: item.goodsId,
                skuId: item.skuId,
                storeId: item.storeId,
              }
              cartItemDel.push(temp);
            })
            batchDeleteItem(cartItemDel).then(res => {
              this.setData({cartItems: []})
              this.handleUpdate()
            })
          }
        }
      });
    },
    handleUpdateNum(e) {
      let data = e.detail;
      let cartItems = this.data.cartItems
      for (let i = 0; i < cartItems.length; i++) {
        if (data.cartItemId === cartItems[i].cartItemId) {
          cartItems[i].num = data.num;
        }
      }
      this.setData({cartItems: cartItems})
      this.initCart(cartItems)
    },
    handleUpdateSelect(e) {
      let data = e.detail;
      let cartItems = this.data.cartItems
      for (let i = 0; i < cartItems.length; i++) {
        if (data.cartItemId === cartItems[i].cartItemId) {
          cartItems[i].selected = data.selected;
        }
      }
      this.setData({cartItems: cartItems})
      this.initCart(cartItems)
    },
    handleSelectAll() {
      if (this.data.detail.errorCode !== 0) {
        return;
      }
      let cartItems = this.data.cartItems
      let selected = !this.data.selectAll;
      let cardItemIdList = [];
      if (this.data.selectAll) {
        // 取消所有选择
        for (let i = 0; i < cartItems.length; i++) {
          if (cartItems[i].disable) {
            continue;
          }
          cardItemIdList.push(cartItems[i].cartItemId)
          cartItems[i].selected = !this.data.selectAll;
        }
      } else {
        // 选择所有
        for (let i = 0; i < cartItems.length; i++) {
          if (cartItems[i].disable) {
            continue;
          }
          if (!cartItems[i].selected) {
            cardItemIdList.push(cartItems[i].cartItemId)
            cartItems[i].selected = true;
          }
        }
      }
      changeSelectState({selected, cardItemIdList}).then((res => {
      }))
      this.setData({cartItems})
      this.initCart(cartItems)
    },
    handleSelectStore() {
      console.info("this.data.detail.deliveryType", this.data.detail.deliveryType)
      if (this.data.detail.deliveryType === 'LOCAL') {
        this.triggerEvent('selectStore', {deliveryType: 'LOCAL_SELF_PICKUP'});
      } else {
        this.triggerEvent('selectStore', {deliveryType: this.data.detail.deliveryType});
      }

    },
    handleUpdate(e) {
      // 先逻辑修改
      this.triggerEvent('update');
    },
    /**
     * 显示删除按钮
     */
    showDeleteButton: function (e) {
      let index = e.currentTarget.dataset.index
      this.setXmove(index, -80)
    },

    /**
     * 隐藏删除按钮
     */
    hideDeleteButton: function (e) {
      let index = e.currentTarget.dataset.index

      this.setXmove(index, 0)
    },

    /**
     * 设置movable-view位移
     */
    setXmove: function (index, xmove) {
      let items = this.data.cartItems;
      if (xmove === 0 && !items[index].xmove) {
        return;
      }
      if (xmove !== 0 && items[index].xmove === xmove) {
        return;
      }
      console.info("setXmove", index, xmove)
      for (let i = 0; i < items.length; i++) {
        if (index === i) {
          items[i].xmove = xmove
        } else {
          items[i].xmove = 0
        }
      }
      this.setData({
        cartItems: items
      })
    },

    /**
     * 处理movable-view移动事件
     */
    handleMovableChange: function (e) {
      if (e.detail.source === 'friction') {
        if (e.detail.x < -30) {
          this.showDeleteButton(e)
        } else {
          this.hideDeleteButton(e)
        }
      } else if (e.detail.source === 'out-of-bounds' && e.detail.x === 0) {
        this.hideDeleteButton(e)
      }
    },

    /**
     * 处理touchstart事件
     */
    handleTouchStart(e) {
      this.startX = e.touches[0].pageX
    },

    /**
     * 处理touchend事件
     */
    handleTouchEnd(e) {
      if (e.changedTouches[0].pageX < this.startX && e.changedTouches[0].pageX - this.startX <= -30) {
        this.showDeleteButton(e)
      } else if (e.changedTouches[0].pageX > this.startX && e.changedTouches[0].pageX - this.startX < 30) {
        this.showDeleteButton(e)
      } else {
        this.hideDeleteButton(e)
      }
    },

    handleDel(e) {
      let index = e.currentTarget.dataset.index;
      let item = this.data.cartItems[index]
      let cartItemDel = [{
        cartItemId: item.cartItemId,
        goodsId: item.goodsId,
        skuId: item.skuId,
        storeId: item.storeId,
      }];
      batchDeleteItem(cartItemDel).then(res => {
        this.handleUpdate()
      })
    },
    async handlePreOrder() {
      let selectCartList = this.data.selectCartItems;
      if (selectCartList.length === 0) {
        return;
      }
      let storeInfo = await getStoreDetail({storeId: this.data.detail.storeId})
      const { storeNo } = storeInfo.data

      let orderPreForm = {
        items: [],
        source: 0,
        storeId: this.data.detail.storeId,
        type: this.data.detail.deliveryType
      };
      console.info()
      selectCartList.forEach(item => {
        orderPreForm.items.push(item)
      })
      wx.showLoading({title: "下单中...", mark: true});
      let deliveryType = this.data.detail.deliveryType
      preOrderFun(orderPreForm).then(res => {
        wx.hideLoading();
        if (res.code === 0) {
          router.push({
            name: 'mall/submit-order',
            params: {preNo: res.data.preNo, deliveryType: deliveryType, storeNo: storeNo},
            success: (res) => {
              if (deliveryType === 'LOCAL') {
                setTimeout(() => {
                  res.eventChannel.emit('showSelectDelivery');
                }, 300)
              }
            }
          })
        }
      }).catch((res)=>{
        if(res.data.data.invalidItems.length>0){
          wx.showToast({
            icon: 'none',
            title:res.data.data.invalidItems[0].title+res.data.data.invalidItems[0].errorMsg,
          })
        }
      })
    }
  }
});
